<?php
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.jucheng01.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: 姜兴明 <jiangxingming@foxmai.com> 2015-4-27
// +----------------------------------------------------------------------
namespace Member\Controller;
use Think\Controller;
use Com\UploadFile;
use Member\Logic\MoudleUrlLogic;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class MemberController extends Controller {
	
	//需要权限的模块
	//protected $noallow = array('mall','website','albums','appcar','microbar','reserve','sctatch','fruit','turntable','stores','survey','tuan','share','generalize','lottery','vote','spike');
	protected $noallow = array();
	/* 空操作，用于输出404页面 */
	public function _empty(){
		//$this->redirect('Index/index');
	}


    protected function _initialize(){
        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置

        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }
        
        $this->login();
        
        //设置代理商信息
        $agent = session('agent');
        $this->assign('AGENT',$agent);
        
        //模块
        $noallow = $this->noallow;
        $controller_name = strtolower(CONTROLLER_NAME);
        $usermodules = session('usermodules');
        if(in_array($controller_name, $noallow) && !in_array($controller_name, $usermodules)){
            $this->error('您当前没有开通该模块');
        }
        $this->noallow = $noallow;
		//dump(CONTROLLER_NAME);
    }

	/** 
	*
	* 用户登录  
	* @copyright Copyright&copy; 2015, 聚成网络 
	* @author Jucheng     
	* @date   2015-4-27  
	* 
	*/
	protected function login(){
		define('UID',is_login());
		// 还没登录 跳转到登录页面
		if( !UID ){
			$this->redirect('User/index');
		}
		
	}
	
	/**
	 * 文件上传
	 * @param file $file 上传的文件信息  $_FILES['photo']
	 * @return array 返回文件的上传信息
	 */
	protected function fileUpload($file){
		
	    import('Com.UploadFile');
	    
	    $up = new UploadFile(array('allowExts'=>array('jpg','jpeg','png','gif','wmp','mp3','xls')));
	    //路径信息
	    $path = '/Upload/'.date('Y',time()).'/'.date('md',time()).'/';
	    
	    $fileinfo = $up->uploadOne($file,ROOT_PATH.'/Public'.$path);
	    
	    $info = $fileinfo[0];
	    
	    // 	$fileinfo = $up->getUploadFileInfo();
	    $info['uppath'] = $path;
	    // 	dump($info);
	    return $info;
	}
	
	public function ajaxFileUpload(){
		//上传图片信息
		$fileinfo = $this->fileUpload($_FILES['Filedata']);
		if(isset($fileinfo['savename']) && !empty($fileinfo['savename'])){
		    $arr = array(
		        	'imgpath'=>C('WEB_ABSOLUTE_URL').'/Public'.$fileinfo['uppath'].$fileinfo['savename'],
		    		'status'=>1,
		    );
		    $this->ajaxReturn($arr,'JSON');
		}else{
			$arr = array(
					'status'=>0,
			);
			$this->ajaxReturn($arr,'JSON');
		}
	}
	
	protected function configs(){
		$data = array(
				'keyword'		=>	I('post.ReplyKeyword'),
				'patternmethod'	=>	I('post.PatternMethod'),
				'title'			=>	I('post.ReplyTitle'),
				'replyimgpath'	=>	I('post.ReplyImgPath'),
				'msgid'			=>	I('post.msgid'),//没用
				'relation'       =>   I('post.relation'),
				'msgtype'       =>   'onenews',
		);
// 		print_r($data);exit;
		if(empty($data['relation'])){
		    $this->ajaxReturn(array('msg'=>'配置信息错误'));
		}
		
		//保存关键词
		$keywordsLogic = D('Keywords','Logic');
		$newsmsgLogic = D('Newsmsg','Logic');
		
		//图文消息
		$newsConfig = array(
				'Title'		=>	$data['title'],
				'ImgPath'	=>	$data['replyimgpath'],
				'BriefDescription'=>"",
				'Url'		=>	$data['relation'],
		);
		$newsData = array(
				'uid'		=>	UID,
				'msgtype'	=>	$data['msgtype'],
				'relation'	=>	$data['relation'],
				'title'	=>	$data['title'],
				'configs'	=>	serializeMysql($newsConfig),
				'createtime'=>	time(),
		);
		
		//查找该图文消息
		$map = array(
		    'uid'=>UID,
// 			'id'=>$data['msgid'],
			'relation'=>$data['relation'],
		);
		$newmsg = $newsmsgLogic->where($map)->find();
		
		if(empty($newmsg) || !isset($newmsg['id'])){
			//添加图文资讯信息
			$newsmsgLogic->add($newsData);
			$msgid = $newsmsgLogic->getLastInsID();
			
		}else{
		    $newsmsgLogic->where($data)->save($newsData);
		    $msgid = $newmsg['id'];
		}
		
// 		dump($msgid);
		
		$keywords_arr = explode(" ", $data['keyword']);
		
		
		
		foreach ($keywords_arr as $k=>$v){
			$v = trim($v);
			
			if(empty($v)){
				unset($keywords_arr[$k]);
			    continue;
			}
			$keywords_arr[$k] = $v;
			
			
			$map = array('keywords'=>$v,'uid'=>UID);
			$keyword = $keywordsLogic->getKeyword($map);
			
			
			
			//关键词信息
			$keyData = array(
					'uid'			=>	UID,
					'msgtype'		=>	$data['relation'],
					'keywords'		=>	$v,
					'matchingtype'	=>	$data['patternmethod'],
			);
			
			//如果当前关键词不存在
			if(empty($keyword)){
			    //添加关键词信息
			    $keyData['msgid'] = $msgid;
			    $status = $keywordsLogic->add($keyData);
			}else{
				
				if($keyword['msgtype'] != $data['relation']){
					$this->ajaxReturn(array('status'=>-1,'msg'=>'关键词['.$keyword['keywords'].']已经被占用'));
				}
				
			    //如果当前存在该关键词，那么只需要更新数据即可
				$map = array('id'=>$keyword['id'],'uid'=>UID);
				$keywordsLogic->where($map)->save($keyData);
				//更新图文消息
				$map = array('uid'=>UID,'id'=>$keyword['msgid']);
				$newsmsgLogic->where($map)->save($newsData);
			}
			
		}
		
		//删除之前的已经存在的关键词的记录
		$map = array(
				'uid'=>UID,
				'msgid'=>$msgid,
				'msgtype'=>$data['relation'],
				'keywords'=>array('NOT IN',$keywords_arr)
		);
		
		$keywordsLogic->where($map)->delete();
// 		echo $keywordsLogic->getLastSql();
		return true;
		
		
	}
	protected function voteconfigs($relation,$vid){
		$data = array(
				'keyword'		=>	I('post.ReplyKeyword'),
				'patternmethod'	=>	I('post.PatternMethod'),
				'title'			=>	I('post.ReplyTitle'),
				'replyimgpath'	=>	I('post.ReplyImgPath'),
				'msgid'			=>	I('post.msgid'),//没用
				'relation'      =>  $relation,
				'msgtype'       =>   'onenews',
		);
		// 		print_r($data);exit;
		if(empty($data['relation'])){
			$this->ajaxReturn(array('msg'=>'配置信息错误'));
		}
	
		//保存关键词
		$keywordsLogic = D('Keywords','Logic');
		$newsmsgLogic = D('Newsmsg','Logic');
	
		//图文消息
		$newsConfig = array(
				'Title'		=>	$data['title'],
				'ImgPath'	=>	$data['replyimgpath'],
				'BriefDescription'=>"",
				'Url'		=>	'vote/index/vid/'.$vid,
		);
		$newsData = array(
				'uid'		=>	UID,
				'msgtype'	=>	$data['msgtype'],
				'relation'	=>	$data['relation'],
				'title'	=>	$data['title'],
				'configs'	=>	serializeMysql($newsConfig),
				'createtime'=>	time(),
		);
	
		//查找该图文消息
		$map = array(
				'uid'=>UID,
				// 			'id'=>$data['msgid'],
				'relation'=>$data['relation'],
		);
		$newmsg = $newsmsgLogic->where($map)->find();
	
		if(empty($newmsg) || !isset($newmsg['id'])){
			//添加图文资讯信息
			$newsmsgLogic->add($newsData);
			$msgid = $newsmsgLogic->getLastInsID();
				
		}else{
			$newsmsgLogic->where($data)->save($newsData);
			$msgid = $newmsg['id'];
		}
	
		// 		dump($msgid);
	
		$keywords_arr = explode(" ", $data['keyword']);
	
	
	
		foreach ($keywords_arr as $k=>$v){
			$v = trim($v);
				
			if(empty($v)){
				unset($keywords_arr[$k]);
				continue;
			}
			$keywords_arr[$k] = $v;
				
				
			$map = array('keywords'=>$v,'uid'=>UID);
			$keyword = $keywordsLogic->getKeyword($map);
				
				
				
			//关键词信息
			$keyData = array(
					'uid'			=>	UID,
					'msgtype'		=>	$data['relation'],
					'keywords'		=>	$v,
					'matchingtype'	=>	$data['patternmethod'],
			);
				
			//如果当前关键词不存在
			if(empty($keyword)){
				//添加关键词信息
				$keyData['msgid'] = $msgid;
				$status = $keywordsLogic->add($keyData);
			}else{
	
				if($keyword['msgtype'] != $data['relation']){
					$this->ajaxReturn(array('status'=>-1,'msg'=>'关键词['.$keyword['keywords'].']已经被占用'));
				}
	
				//如果当前存在该关键词，那么只需要更新数据即可
				$map = array('id'=>$keyword['id'],'uid'=>UID);
				$keywordsLogic->where($map)->save($keyData);
				//更新图文消息
				$map = array('uid'=>UID,'id'=>$keyword['msgid']);
				$newsmsgLogic->where($map)->save($newsData);
			}
				
		}
	
		//删除之前的已经存在的关键词的记录
		$map = array(
				'uid'=>UID,
				'msgid'=>$msgid,
				'msgtype'=>$data['relation'],
				'keywords'=>array('NOT IN',$keywords_arr)
		);
	
		$keywordsLogic->where($map)->delete();
		// 		echo $keywordsLogic->getLastSql();
		return true;
	
	
	}
	/** 
	*
	* 获取链接页面
	* @copyright Copyright&copy; 2015, 聚成网络 
	* @author 姜兴明  
	* @date   2015-4-30  
	* 
	*/
	protected function linkurl(){
		
		$LinkurlLogic = D('Linkurl','Logic');
		$linkurl = $LinkurlLogic->allLists();
		$this->assign('linkurl',$linkurl);
	}
	
	/** 
	*
	* 获取access_token 上次获取时间跟现在差距大于7200秒则重新获取  
	* @copyright Copyright&copy; 2015, 聚成网络 
	* @author 姜兴明  
	* @date   2015-4-30  
	* 
	*/
	
	public function getAccessToken(){
		$userconfigLogic = D('Userconfig','Logic');
		$userconfiginfo = $userconfigLogic->where(array('uid'=>UID))->find();
		$time = time();
		$new_access_token = $userconfiginfo['access_token'];
		if($userconfiginfo['access_token'] == null || $time > $userconfiginfo['access_time']+7200){
			$userinfo = $userconfiginfo;
			$appid = $userinfo['appid'];
			$appsecret = $userinfo['appsecret'];
			//非oauth2的方式获得全局access token
			$new_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
			$new_access_token_json = $this->https_request($new_access_token_url);
			$new_access_token_array = json_decode($new_access_token_json, true);
			$new_access_token = $new_access_token_array['access_token'];
			$data = array(
					'access_token' => $new_access_token,
					'access_time' => time(),
			);
			$res = $userconfigLogic->where(array('uid'=>UID))->save($data);
		}
	//dump($new_access_token);
		return $new_access_token;
	}
	
	/** 
	*
	* Http请求  
	* @copyright Copyright&copy; 2015, 聚成网络 
	* @author 姜兴明  
	* @date   2015-4-30  
	* 
	*/

	public function https_request($url){
	
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($curl);
		if (curl_errno($curl)){return 'ERROR '.curl_error($curl);}
		curl_close($curl);
		return $data;
	
	}
	
	
	
	public function sendSms($phonenumber,$content){
		$data = array (
				'action' => 'send', //发送任务命令
				'account' => 'emeijia', //账号
	  			'password' => '111111', //密码
				'mobile' => $phonenumber, //手机号
				'content' => $content, //内容
				'sendTime' => time(), //发送时间
				'AddSign' => 'Y'  //是否自动加上系统配置默认的签名
		);
		$url = 'http://www.smswst.com/api/httpapi.aspx?action=send&account='.$data['account'].'&password='.$data['password'].'&mobile='.$data['mobile'].'&content='.$data['content'].'&sendTime=&AddSign=Y';
		$return = $this->httpPostData($url);
		//dump($return);
		$return = $this->xmlToArray($return);
		$data['returncode'] = $return['successCounts'];
		$data['config'] = serializeMysql($return);
		$smsLogic = D('Sms','Logic');
		$smsLogic->add($data);
	}
	
	
	/**
	 * http带参数请求
	 * @date: 2015-1-31
	 * @author: 明
	 * @return:
	 */
	public function httpPostData($url,$data){
		$data = JSON($data,false);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$status = curl_exec($ch);
		curl_close($ch);
		return $status;
	}
	
	public function xmlToArray($xml)
	{
		//将XML转为array
		$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return $array_data;
	}
	

	/**
	 * 美容项目短信请求
	 * @date: 2015-9-2
	 * @author: 刘炎炎
	 * @return:
	 */
	public function sendMassage($phone,$content){
		$time = time();
		$post_data = array();
		$post_data['userid'] = '5710';//企业ID
		$post_data['timestamp']=date("YmdHis",$time);//当前时间戳
		$post_data['sign']=strtolower(md5('ZK11123456'.(date("YmdHis",$time))));//MD5（账号密码当前时间戳）
		$post_data['content'] = $content.'【易美佳人】'; //格式为：内容【签名】
		$post_data['mobile'] = $phone;//手机号
		$post_data['sendtime'] = ''; //不定时发送，值为‘’，定时发送，输入格式YYYYMMDDHHmmss的日期值
		$url='http://xtx.telhk.cn:8080/v2sms.aspx?action=send';
		$o='';
		foreach ($post_data as $k=>$v)
		{
			$o .= "$k=".urlencode($v).'&';
			//dump($o);
		}
		 
		$post_data=substr($o,0,-1);
		 
		$ch = curl_init();
		 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
		$result = curl_exec($ch);
	}
	
	
	/**
	 * 推动模板消息并生成log记录
	 * @date: 2015-1-31
	 * @author: 明
	 * @data：$data 模板消息内容  $
	 * @return:$res 返回的数据
	 */
	public function sendtemplate($data){
		 
		$access_token = $this->getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
		//dump($url);
		//exit;
		//buchongjilu模板消息的算法
		$res = $this->httpdata($url, $data);
		//dump($res);
		 
	}
	
	/**
	 * http带参数请求
	 * @date: 2015-1-31
	 * @author: 明
	 * @return:
	 */
	public function httpdata($url,$data){
		$data = json_encode($data);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$status = curl_exec($ch);
		curl_close($ch);
		$res = json_decode($status,true);
		return $res;
	}
	 
	

	
}
